<template>
  <div v-loading="loading" class="gl_mb_15">
    <div>
      <el-row v-if="groupData.length > 0" class="report_title" type="flex" justify="space-between">
        <el-col :span="8">
          <el-button v-if="groupApproveStatus.code == 'ApproveFailed'" type="primary" size="mini" @click="dialogVisible = true">查看驳回原因</el-button>
          <el-button v-if="groupApproveStatus.code == 'ApproveFailed'" type="primary" size="mini" @click="jumpToGameEntry">修改</el-button>
        </el-col>
        <el-col :span="14" align="right" class="gl_pt_5 approve">
          <span>审核状态：</span>
          <span v-if="groupApproveStatus.code == 'ApproveSuccess'" class="gl_color_success gl_pr_15">{{ groupApproveStatus.name }}</span>
          <span v-else class="gl_color_warning">{{ groupApproveStatus.name }}</span>
          <el-button
            v-if="groupApproveStatus.code !== 'ApproveFailed'"
            style="margin-left: 10px;"
            type="primary"
            size="mini"
            @click="exportOrder(groupApproveStatus.code)"
          >
            下载表单
          </el-button>
          <el-button  style="margin-left: 10px;"  size="mini" type="primary" @click="clickWorld()" :loading="entryWorld">下载报名明细</el-button>
        </el-col>
      </el-row>
      <el-dialog title="驳回原因" class="gl_dialog_TitleLine" :visible.sync="dialogVisible" width="440px">
        <p>{{ groupApproveRemark }}</p>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="dialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
      <el-radio-group v-model="tabPosition" style="margin-bottom: 0px;" @change="actother">
        <el-radio-button label="remote">运动员</el-radio-button>
        <el-radio-button label="other">其他赛事人员</el-radio-button>
      </el-radio-group>
      <div v-if="tabPosition === 'remote'">
        <el-table key="tab01" v-loading="groupLoading" :data="groupData" size="mini">
          <el-table-column type="index" width="50" align="center" />
          <el-table-column prop="name" label="姓名" width="140" />
          <el-table-column prop="sourceRegister.genderCode" label="性别" width="50" align="center">
            <template slot-scope="{row}">
              <span v-for="item in dict.gender" :key="item.code">
                {{ item.code === row.sourceRegister.genderCode ? item.value : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="sourceRegister.idCardNumber" label="证件号码" width="150" align="center" />
          <template v-if="competition.isFinal && competition.parentId">
            <el-table-column prop="subCompetition.name" label="赛区" width="100" align="left" />
          </template>
          <el-table-column prop="delegation.name" label="参赛机构" width="160">
            <template slot-scope="{row}">
              <el-tooltip :content="row.delegation.name" placement="left" effect="light">
                <p class="gl_ellipsis">{{ row.delegation.name }}</p>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="entrys" label="个人项目">
            <template slot-scope="{row}">
              <div v-for="(item, index) in row.entrys" :key="item.id">
                <el-tooltip :content="item.event.longName + `${item.weightClass ? ' (' + item.weightClass.name + ') ' : '' }` + `${item.teamNo ? item.teamNo + '组' : '' }`" placement="left" effect="light">
                  <p v-if="item.event.registerTypeCode == 'I'" class="gl_ellipsis">
                    <span>{{ item.event.longName }}</span>
                    <span v-if="item.weightClass">{{ ' (' + item.weightClass.name + ') ' }}</span>
                    <span v-if="item.teamNo">{{ item.teamNo }}组</span>
                    <span v-if="index !== row.entrys.length - 1">；</span>
                  </p>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="entrys" label="团体项目">
            <template slot-scope="{row}">
              <div v-for="(item, index) in row.entrys" :key="item.id">
                <el-tooltip :content="item.event.longName + `${item.weightClass ? ' (' + item.weightClass.name + ') ' : '' }` + `${item.teamNo ? item.teamNo + '组' : '' }`" placement="left" effect="light">
                  <p v-if="item.event.registerTypeCode != 'I'" class="gl_ellipsis">
                    <span>{{ item.event.longName }}</span>
                    <span v-if="item.weightClass">{{ ' (' +item.weightClass.name + ') ' }}</span>
                    <span v-if="item.teamNo">{{ item.teamNo }}组</span>
                    <span v-if="index !== row.entrys.length - 1">；</span>
                  </p>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="资质审查" width="80" align="center">
            <template slot-scope="{row}">
              <el-button type="text" @click="dataUpload(row.id)">资料上传</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-table key="tab02" v-loading="groupLoading" :data="othertable" size="mini">
          <el-table-column type="index" width="50" label="序号" align="center" />
          <el-table-column prop="name" label="姓名" width="160" />
          <el-table-column prop="gender.name" label="性别" width="50" align="center" />
          <el-table-column prop="idCardNumber" label="证件号码" width="150" align="center" />
          <el-table-column prop="registerTagType.name" label="人员类型" align="center" />
        </el-table>
      </div>
      <el-row class="gl_pt_20" style="text-align: center;">
        <el-pagination
          :current-page="groupForm.Page"
          :page-size="groupForm.MaxResultCount"
          :total="groupTotalPage"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="groupSizeChange"
          @current-change="groupPageIndexChange"
        />
      </el-row>
    </div>
    <UploadData ref="uploadData" />
  </div>
</template>

<script>
import {
  api_GET_EventsManagemententrybyOtherPerson, // 查询运动员以外的报项人员
  api_GET_EventsManagementEntryByPerson, // 查询报项（按个人汇总报项）
  api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalList // 获取审核状态
} from '@/extend/api/gameswaggerApi/app.js';
import {
  Api_GET_EventsManagementEntryByPersonQO,
  Api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalListQO
} from '@/lib/form/game/swaggerForm';
import UploadData from './uploadData';
import { mapState, mapActions } from 'vuex';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
export default {
  name: 'Group',
  components: {
    UploadData
  },
  props: {
    competition: {
      required: true,
      type: Object,
      default() { return {}; }
    }
  },
  data() {
    return {
      entryWorld: false,
      tabPosition: 'remote',
      loading: false,
      groupLoading: false,
      exportLoading: false,
      dialogVisible: false,
      Api_GET_EventsManagementEntryByPersonQO: new Api_GET_EventsManagementEntryByPersonQO(),
      ApprovalCompetitionEntryApprovalListQO: new Api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalListQO(),
      groupForm: {}, // 查询团体报项单所用表单
      delegationId: '',
      registerId: '',
      groupTotalPage: 0,
      groupApproveStatus: {}, // 团体报项单状态
      groupApproveRemark: '', // 驳回原因
      groupData: [], // 团体报项单信息
      gameId: '',
      othertable: []
    };
  },
  computed: {
    ...mapState({
      currentUserType: state => state.user.currentUserType,
      dict: state => state.dict.dict
    }),
    groupPlayersList () {
      return this.groupData.map(item => item.sourceRegister);
    }
  },
  watch: {
    'currentUserType': {
      handler: function(val) {
        if (val) {
          this.gameId = this.$route.query.id;
          this.delegationId = val.delegationId;
          this.registerId = val.registerId;
          this.getGroupApproval();
        }
      },
      deep: true,
      immediate: true // 初始加载
    }
  },
  created() {
    this.gameId = this.$route.query.id;
    this.getDict();
    if (this.Api_GET_EventsManagementEntryByPersonQO) {
      this.groupForm = JSON.parse(JSON.stringify(this.Api_GET_EventsManagementEntryByPersonQO));
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取团体报项单状态
    getGroupApproval() {
      var that = this;
      that.loading = true;
      const form = JSON.parse(JSON.stringify(that.ApprovalCompetitionEntryApprovalListQO));
      form.CompetitionId = that.gameId;
      form.IsDelegation = true;
      form.EntryScopeId = that.delegationId;
      api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalList(form).then(res => {
        that.groupApproveStatus = res.items.length > 0 ? res.items[0].approval.approveStatus : '';
        that.groupApproveRemark = res.items.length > 0 ? res.items[0].approval.approveRemark : '';
        if (that.groupApproveStatus) {
          that.getDetailGroup();
        }
        that.loading = false;
      }).catch(() => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取团体报项单失败' });
      });
    },
    // 获取团体报项单
    getDetailGroup(page) {
      var that = this;
      that.groupLoading = true;
      that.groupForm.Page = page || 1;
      that.groupForm.SkipCount = (that.groupForm.Page - 1) * that.groupForm.MaxResultCount;
      that.groupForm.CompetitionId = that.$route.query.id;
      that.groupForm.DelegationId = that.delegationId;
      that.groupForm.CompEntryApproveStatusCode = that.groupApproveStatus.code;
      if (this.tabPosition === 'remote') {
        api_GET_EventsManagementEntryByPerson(that.groupForm).then(res => {
          that.groupData = res.items;
          that.groupTotalPage = res.totalCount;
          that.groupLoading = false;
        }).catch(() => {
          that.groupLoading = false;
        });
      } else {
        api_GET_EventsManagemententrybyOtherPerson(that.groupForm).then(res => {
          that.othertable = res.items;
          that.groupTotalPage = res.totalCount;
          that.groupLoading = false;
        }).catch(() => {
          that.groupLoading = false;
        });
      }
    },
    actother() {
      console.log(this.tabPosition);
      this.getGroupApproval();
    },
    // 团体报项单分页
    groupSizeChange(MaxResultCount) {
      this.groupForm.MaxResultCount = MaxResultCount;
      this.getDetailGroup();
    },
    groupPageIndexChange(currentPage) {
      this.getDetailGroup(currentPage);
    },
    // 资料上传
    dataUpload(id) {
      this.$refs.uploadData.open(id);
    },
    // 跳转至赛事报名页面重新走流程
    jumpToGameEntry () {
      const _gameRoute = this.competition.route;
      this.$router.push({
        path: '/home/' + _gameRoute + '/enter?modifyType=Delegation'
      });
    },
    clickWorld() {
      var that = this;
      this.entryWorld = true;
      const tempUrl = `/api/app/events-management/report`;
      const fileName = '报名明细' + '.pdf';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'EntryByDelegation',Format: 'PDF', CompetitionId: that.$route.query.id,DelegationId: that.delegationId }).then(res => {
        that.entryWorld = false;
      }).catch(error => {
        that.entryWorld = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 下载秩序册
    exportOrder(res) {
      var that = this;
      that.exportLoading = true;
      const tempUrl = `/api/app/events-management/report`;
      const fileName = '秩序册' + '.doc';
      let code = null;
      if (res === 'ApproveSuccess') {
        code = 'ProgrammeByEvent';
      } else {
        code = 'ProgrammeByEventAll';
      }
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: code, Format: 'DOC', CompetitionId: that.$route.query.id, DelegationId: that.delegationId }).then(res => {
        that.exportLoading = false;
      }).catch(error => {
        that.exportLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    }
  }
};
</script>

<style scoped>
.report_title {
  vertical-align: middle;
  padding-bottom: 20px;
  /* border-bottom: 1px solid #DCDFE6; */
}
.approve {
  font-size: 14px;
  vertical-align: middle;
}
.divider_title {
  font-size: 16px;
  color: #353434;
  font-weight: bold;
  line-height: 20px;
}

.dialog_wrap {
  padding: 0 20px;
}
</style>
